package com.d404.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.alibaba.fastjson.JSON;
import com.d404.server.GetGroup.Download;
import com.d404.server.GetGroup.Download.Group;
import com.d404.server.GetGroup.Download.Group.Friend;
import com.d404.server.GetGroup.Upload;

import helpers.BeanHelper;
import im.beans.Group_User;
import im.beans.User;
import manager.PersistentManager;

/**
 * Servlet implementation class GetOwnGroup
 */
// @WebServlet("/GetOwnGroup")
public class GetOwnGroup extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetOwnGroup() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// response.getWriter().append("Served at:
		// ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		String data = request.getParameter("data");
		Upload upload = JSON.parseObject(data, Upload.class);

		Download download = new Download();
		download.setGroups(new ArrayList<Group>());

		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
//		Session session = sf.openSession();
		Session session = sf.getCurrentSession();
		Transaction tx = session.beginTransaction();

		try {
			// // 获取最后一次获取群组的时间
			// User u = (User) session.get(User.class, upload.getUserID());
			// long timestamp = u.getTimestamp();
			// 获取自己所拥有的群组
			Query q = session.createQuery("from Group g where g.ownerID = ?");
			q.setParameter(0, upload.getUserID());
			List<im.beans.Group> gus = q.list();
			for (im.beans.Group g : gus) {
				// 所拥有的群组信息
				Group gBack = new Group();
				gBack.setCrateTime(g.getCreateTime() + "");
				gBack.setGroupID(g.getId());
				gBack.setGroupName(g.getGroupName());
				gBack.setOwnerID(g.getOwnerID() + "");
				gBack.setOwnerName(g.getOwnerName());
				gBack.setFriends(new ArrayList<Friend>());

				// 获取群组中的用户
				Query qUsers = session.createQuery("from Group_User gu where gu.group = ?");
				qUsers.setParameter(0, g);
				List<Group_User> users = qUsers.list();
				for (Group_User guTemp : users) {
					User uTemp = guTemp.getUser();
					Friend f = new Friend();
					f.setFriendID(uTemp.getId());
					f.setFriendName(uTemp.getAccount());
					f.setRealName(guTemp.getRealName());
					// 添加群组用户
					gBack.getFriends().add(f);
				}
				gBack.setUserCount(users.size());
				// 添加群组
				download.getGroups().add(gBack);
			}
			session.getTransaction().commit();
			download.setStatus(Download.SUCCESS);
		} catch (Exception e) {
			tx.rollback();
			download.setStatus(Download.FAILED);
			e.printStackTrace();
		} finally {
//			session.close();
		}

		// 去除空格
		for (Group g : download.getGroups()) {
			for (Friend f : g.getFriends()) {
				try {
					BeanHelper.beanAttributeValueTrim(f);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		System.out.println(JSON.toJSONString(download));
		response.setCharacterEncoding("UTF-8");
		response.getWriter().append(JSON.toJSONString(download));

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
